package ttelectronic.mobileholder.service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import ttelectronic.mobileholder.common.MHCommon;
import android.bluetooth.BluetoothSocket;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class MHAlarmService extends Thread {
	private OutputStream mOutStream;
	private Context mContext;

	public MHAlarmService(BluetoothSocket socket, Context context) {
		mContext = context;
		try {
			mOutStream = socket.getOutputStream();
		} catch (IOException e) {
		}
	}

	public void run() {
		super.run();
		while (true) {
			ContentResolver contentResolver = mContext.getContentResolver();
			long ntime = System.currentTimeMillis();
			Log.d(MHCommon.TAG + "ntime", "ntime " + ntime);
			Cursor cursr = contentResolver.query(
					Uri.parse("content://com.android.calendar/events"),
					new String[] { "calendar_id", "title", "description",
							"dtstart", "dtend", "eventLocation" }, null, null,
					null);

			cursr.moveToFirst();
			Log.d(MHCommon.TAG, "Alarm found(s): " + cursr.getCount());
			for (int i = 0; i < cursr.getCount(); i++) {
				long StartTime = cursr.getLong(3);
				if (StartTime <= ntime + 300000 && StartTime >= ntime - 300000) {
					Log.d(MHCommon.TAG + "Alarm ", "ALARM COMMING...");
					PrintWriter pWriter = new PrintWriter(
							new OutputStreamWriter(mOutStream));
					pWriter.write(MHCommon.POSTMSG_ALARM_INCOMING);
					pWriter.flush();
				}
				cursr.moveToNext();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursr.close();
		}
	}
}
